<template>
  <div class="wrap">
    <img data-src='/static/lazyload/1.jpg' src='/static/default.png' >
    <img data-src='/static/lazyload/2.jpg' src='/static/default.png' >
    <img data-src='/static/lazyload/3.jpg' src='/static/default.png' >
    <img data-src='/static/lazyload/4.jpg' src='/static/default.png' >
    <img data-src='/static/lazyload/5.jpg' src='/static/default.png' >
    <img data-src='/static/lazyload/6.jpg' src='/static/default.png' >
    <img data-src='/static/lazyload/7.jpg' src='/static/default.png' >
  </div>
</template>

<script>
  import { throttle } from '@/utils/util.js'

  export default {
    methods: {
      handleLazyLoad () {
        // console.log(`count => 11`)
        const viewH = document.documentElement.clientHeight
        const scrollTop = document.body.scrollTop || document.documentElement.scrollTop

        const images = document.getElementsByTagName('img')
        const len = images.length
        const startIndex = this.startIndex || 0

        if (startIndex === len - 1) return

        for (let i = startIndex; i < len; i ++) {
          if (images[i].offsetTop < viewH + scrollTop) {
            if (images[i].getAttribute('src') === '/static/default.png') {
              images[i].setAttribute('src', images[i].getAttribute('data-src'))
              this.startIndex = i
            }
          }
        }
      }
    },
    mounted() {
      this.handleLazyLoad()
      window.onload = () => this.handleLazyLoad()
      window.addEventListener('scroll', throttle(this.handleLazyLoad, 300))
    }
  }
</script>

<style lang="stylus" scoped>
.wrap
  text-align center
img
  width 600px
  height 400px
  margin 50px auto
  display block
</style>
